package com.zmn.plat.business.impl.message;

import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.plat.business.interfaces.message.MsgTemplateGroupBService;
import com.zmn.plat.model.entity.message.MsgTemplateGroup;
import com.zmn.plat.services.interfaces.message.MsgTemplateGroupService;

/**
 * MsgTemplateConfigService 模板组BServiceImpl
 *
 * @author tanghongjun
 */
@Service
public class MsgTemplateGroupBServiceImpl implements MsgTemplateGroupBService {
    @Resource
    MsgTemplateGroupService msgTemplateGroupService;

    @Override
    public Integer insert(MsgTemplateGroup msgTemplateGroup, String creater) {
        boolean flag = this.checkNameIsRepeat(msgTemplateGroup);
        if (flag) {
            return GlobalConsts.NO;
        }
        msgTemplateGroup.setStatus(GlobalConsts.NO);
        msgTemplateGroup.setCreater(creater);
        msgTemplateGroup.setCreateTime(DateUtil.getNow());
        msgTemplateGroupService.insert(msgTemplateGroup);
        return GlobalConsts.YES;
    }

    @Override
    public Integer updateByKey(MsgTemplateGroup msgTemplateGroup, String updater) {
        boolean flag = this.checkNameIsRepeat(msgTemplateGroup);
        if (flag) {
            return GlobalConsts.NO;
        }
        msgTemplateGroup.setUpdater(updater);
        msgTemplateGroup.setUpdateTime(DateUtil.getNow());
        msgTemplateGroupService.updateByKey(msgTemplateGroup);
        return GlobalConsts.YES;
    }

    /**
     * 描述: 校验模板组名称是否重复
     *
     * @param msgTemplateGroup
     * @return true 重复 false不重复
     * @auther tanghongjun
     * @since 2019/10/24 14:00
     */
    private boolean checkNameIsRepeat(MsgTemplateGroup msgTemplateGroup) {
        MsgTemplateGroup templateGroup = msgTemplateGroupService.fingByNameAndModuleAndPlat(msgTemplateGroup.getName(), msgTemplateGroup.getModule(), msgTemplateGroup.getPlat());
        // 如果数据库没有对应数据，表示不重复
        if (Objects.isNull(templateGroup)) {
            return false;
        }

        // 如果数据库存在数据，但是是新增模板组，表示重复
        if (Objects.isNull(msgTemplateGroup.getGroupId())) {
            return true;
        }

        // 如果是修改同一条数据，表示不重复
        if (Objects.equals(msgTemplateGroup.getGroupId(), templateGroup.getGroupId())) {
            return false;
        }
        return true;
    }
}
